#include "gameclient.h"

#include <game/networkplayer.h>
#include <game/localplayer.h>

#include <QUdpSocket>
#include <QNetworkInterface>
#include <QDomDocument>

#include <QDebug>

GameClient::GameClient(KeyManager *manager, QString adr, quint16 port, QObject *parent) : Game(manager, parent)
{
    mySocket = new QUdpSocket(this);

    QHostAddress address;

    //QStringList items;

    foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces()) {
        if (interface.flags().testFlag(QNetworkInterface::IsRunning)) {
            foreach (QNetworkAddressEntry entry, interface.addressEntries()) {
                if (interface.hardwareAddress() != "00:00:00:00:00:00" && entry.ip().toString().contains("."))
                    //items << interface.name() + entry.ip().toString();
                    address = entry.ip();
            }
        }
    }
    //QHostAddress::
    qDebug("%s", address.toString().toStdString().c_str());
    for (int i = 10000; i < 10100; ++i) {
        if (mySocket->bind(address, i)) {
            break;
        }
    }
    connect(mySocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));

    myServerAddr = QHostAddress(adr);
    myPort = port;
    QByteArray array("subscribe");
    array = qCompress(array);
    mySocket->writeDatagram(array, array.size(), myServerAddr, myPort);

    first = true;
}

void GameClient::timerEvent(QTimerEvent *e) {
    Game::timerEvent(e);
}

void GameClient::play() {
    Game::play();

    QByteArray array;
    array.append(QString("<Command>\n  <ChangeState>%1</ChangeState>\n</Command>").arg(getState()));
    array = qCompress(array);
    mySocket->writeDatagram(array, array.size(), myServerAddr, myPort);
}

void GameClient::pause() {
    Game::pause();

    QByteArray array;
    array.append(QString("<Command>\n  <ChangeState>%1</ChangeState>\n</Command>").arg(getState()));
    array = qCompress(array);
    mySocket->writeDatagram(array, array.size(), myServerAddr, myPort);
}

void GameClient::readPendingDatagrams() {
    while (mySocket->hasPendingDatagrams()) {
        QByteArray array;
        array.resize(mySocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 port;

        mySocket->readDatagram(array.data(), array.size(), &sender, &port);

        QString message = qUncompress(array);

        QDomDocument doc("XML");
        doc.setContent(message);
        QDomNode root = doc.firstChild();
        if(first) {
            qDebug() << message;
            deserializeMe(root.firstChild());

            if(getState() == "playing") {
                play();
            }
            qDebug() << getState();
            qDebug() << getPlayers().size();
            emit updated();
            first = false;

            foreach(Player *pl, myPlayers) {
                if(pl->getType() == "LocalPlayer") {
                    LocalPlayer *lpl = (LocalPlayer *)pl;
                    lpl->setSocket(mySocket, myServerAddr, myPort);
                }
            }
            qDebug() << "set";

        } else {
            deserializeCommand(root);
        }
    }
}
